<template>
	<notice :notice.sync="notice"></notice>
    <header-paper action="testPaper" :cla-id="paper.class_cla_id"></header-paper>
    
    <div class="loading" v-show="loading">
        <i class="fa fa-spinner fa-spin fa-3x"></i>
    </div>

    <div class="container" data-spy="scroll" data-target="#scrollspy" id="question-container" v-show="!loading">
        <!-- <div class="row">
            <button class="btn" @click="items.push({name: 'Item '+(items.length+1), id: items.length, order: items.length})">add</button>
            <ul class="list-group" id='order-list'>
                <li class="list-group-item" 
                    v-for="item in items">
                    {{ item.name }} - ({{ item.order}})
                </li>
            </ul>
        </div> -->
        <div class="row">
            <div class="col-md-4 col-md-offset-2">
                <span class="quiz-name">{{ paper.qus_name }}</span> 
                <span class="text-muted">{{ paper.qus_create_time }}</span>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 col-md-offset-2">
                <button class="btn btn-primary" v-on:click="chagePaperStatus()" v-if="paper.qus_status == 0">开始测试</button>
                <button class="btn btn-default" v-on:click="chagePaperStatus()" v-if="paper.qus_status == 1">结束测试</button>
                <button class="btn btn-default" v-on:click="chagePaperStatus()" v-if="paper.qus_status == 2">继续测试</button>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-2" id="scrollspy">
                <ul class="nav nav-tabs nav-stacked" data-spy="affix" data-offset-top="180">
                    <li>选择试题类型</li>
                    <template v-for="item in TYPETEXT">
                        <li><button class="btn btn-link" v-on:click="appendQue($index)">{{ item }}</button></li>
                    </template>
                </ul>
            </div>
            <div class="col-sm-9">
                <ul class="sortable-list">
                    <li v-for="que in ques" >
                        <paper-item :que="que"
                                    :index="$index"
                                    @msg="showMsg"
                                    @del-que="beforeDelQue($index)"
                                    @cancel-edit="cancelEdit($index)"
                                    @save-que="saveQue($index)">
                        </paper-item>
                    </li>
                </ul>
                
            </div>
        </div>
    </div>

    <modal type="modal-sm" id="del-que">
        <h4 slot="header" class="modal-title text-danger">删除题目</h4>
        <p slot="body">确定删除题目 <span class="text-info">{{ques[delIndex]&&ques[delIndex].que_num}}</span> 吗</p>
        <button slot="footer" type="button" class="btn btn-danger" @click="delQue()">删除</button>
    </modal>

</template>

<script>
	import HeaderPaper from '../../Component/HeaderPaper/HeaderPaper';
    import Notice from '../../Component/Notice/Notice';
    import PaperItem from '../../Component/PaperItem/PaperItem';
    import Modal from '../../Component/Modal/Modal';
    import Sortable from 'sortablejs';


    export default {
        created: function() {
            this.getPaper();
            this.getPaperInfo();
        },
        ready: function() {
            var vm = this;
            Sortable.create(document.getElementsByClassName('sortable-list')[0], {
                animation: 250,
                handle: '.handle',
                filter: '.ignore-elements',
                onStart: function (event) {
                    if (!vm.sortable) {
                        vm.notice = {type: 0, msg: '请先保存所有正在编辑的题目再进行排序'};
                    }
                },  
                onMove: function (event) {
                    if (!vm.sortable) {
                        return false;
                    }
                },
                onUpdate: function(event) {
                    
                    vm.$http.post('/question/move', 
                        {que_id1: vm.ques[event.oldIndex].que_id, que_id2: vm.ques[event.newIndex].que_id}).then(function(resp) {
                            if (resp.data.status === 1) {
                                vm.notice = {type: 1, msg: "移动成功"};
                            } else {
                                vm.notice = {type: 0, msg: resp.data.message};
                            }
                    }, function(resp) {
                        // error callback
                        vm.notice = {type: 0, msg: resp.statusText};
                    })
                    vm.ques.splice(event.newIndex, 0, vm.ques.splice(event.oldIndex, 1)[0]);
                    vm.ques.forEach((item, index) => {
                        item.que_num = index+1;
                    })
                }
            })
        },
        data() {
            return {
                tpId: location.search.slice(1).split('=')[1],
                notice: {type: 0, msg: ""},
                loading: false,
                paper: {},
                ques: [],
                delIndex: -1,
                TYPETEXT : ["判断题", "单选题", "多选题", "填空题", "简答题"]
            }
        },
        computed: {
            sortable () {
                return this.ques.every((value) => {
                    return !value.editing
                })
            }
        },
    	components: {
    		HeaderPaper,
    		Notice,
            PaperItem,
            Modal
    	},
        methods: {
            getPaper: function() {
                this.loading = true;
                this.$http.post('/question/question', {qus_id: this.tpId}).then(function(resp) {
                    this.loading = false;
                    if (resp.data.status === 1) {
                        var ques = resp.data.data;

                        ques.forEach((value) => {
                            value.editing = false;
                            // 将选项保存到数组
                            value.que_items = [];
                            for (let i = 1; i <= 8; i++) {
                                if (value["que_item"+i]) {
                                    value.que_items.push(value["que_item"+i]);
                                }
                                delete value["que_item"+i];
                            }
                            if (value.que_type < 2) {
                                value.que_answer = value.que_answer === '' ? -1 : value.que_answer;
                            } else if (value.que_type == 2) {
                                value.que_answer = value.que_answer.split("");
                            }
                            // 备份题目中能修改的项
                            value.contentBak = value.que_content;
                            value.scoreBak = value.que_score;
                            value.itemsBak = value.que_items.concat();
                            value.answerBak = value.que_type==2?value.que_answer.concat():value.que_answer;
                        })
                        this.ques = ques;

                    } else {
                        this.notice = {type: 0, msg: resp.data.message};
                    }
                }, function(resp) {
                    // error callback
                    this.loading = false;
                    this.notice = {type: 0, msg: resp.statusText};
                })
            },
            getPaperInfo: function() {
                this.$http.post('/questionSet/getQuizInfo', {qus_id: this.tpId}).then(function(resp) {
                    if (resp.data.status === 1) {
                        this.paper = resp.data.data;
                    }
                }, function(resp) {
                    // error callback
                    this.notice = {type: 0, msg: resp.statusText};
                })
            },
            showMsg: function(msg, type) {
                this.notice = {type: type, msg: msg};
            },
            beforeDelQue: function(index) {
                this.delIndex = index;
                $('#del-que').modal('toggle');
            },
            delQue: function() {
                var postData = {
                    qus_id: this.paper.qus_id, 
                    que_id: this.ques[this.delIndex].que_id
                };
                this.$http.post('/question/delete', postData).then(function(resp) {
                    if (resp.data.status === 1) {
                        this.notice = {type: 1, msg: resp.data.message};
                        // 备份
                        for (let i = this.delIndex+1; i < this.ques.length; i++)
                            this.ques[i].que_num--;
                        this.ques.splice(this.delIndex, 1);
                    } else {
                        this.notice = {type: 0, msg: resp.data.message};
                    }
                }, function(resp) {
                    // error callback
                    this.notice = {type: 0, msg: resp.statusText};
                })
                $('#del-que').modal('toggle');
            },
            appendQue: function(index) {
                var que = {
                    que_type: index,
                    que_content: '',
                    que_num: this.ques.length+1,
                    que_items: [],
                    que_score: '',
                    que_answer: '',
                    editing: true
                }
                if (index === 0) {
                    que.que_items = ['对', '错'];
                    que.que_answer = -1;
                } else if (index === 1) {
                    que.que_items = ['','','',''];
                    que.que_answer = -1;
                }  else if (index === 2) {
                    que.que_items = ['','','',''];
                    que.que_answer = [];
                } else if (index === 3) {
                    que.que_answer = '';
                } else if (index === 4) {
                    que.que_answer = '';
                    que.que_score = '0';
                }
                this.$broadcast('append-que');
                this.ques.push(que);
                $('html,body').animate({scrollTop:document.body.scrollHeight});
            },
            cancelEdit: function(index) {
                var que = this.ques[index];
                if (que.que_id) {
                    que.editing = false;
                    que.que_content = que.contentBak;
                    que.que_score = que.scoreBak;
                    que.que_items = que.itemsBak.concat();
                    que.que_answer = que.que_type==2?que.answerBak.concat():que.answerBak;
                } else {
                    for (let i = index+1; i < this.ques.length; i++)
                        this.ques[i].que_num--;
                    this.ques.splice(index, 1);
                }
            },
            saveQue: function(index) {
                var postData = {},
                    que = this.ques[index],
                    postUrl = que.que_id? '/question/update' : '/question/add';
                // 选项
                if (que.que_type < 3) {
                    que.que_items.forEach((value, index) => {
                        postData['que_item'+(index+1)] = value;
                    })
                }
                // 答案
                if (que.que_type == 2) {
                    postData['que_answer'] = que.que_answer.join("");
                } else {
                    postData['que_answer'] = que.que_answer === -1 ? '' : que.que_answer;
                }
                // 其他
                postData['que_type'] = que.que_type;
                postData['que_score'] = que.que_score;
                postData['que_content'] = que.que_content;
                postData['que_id'] = que.que_id;
                postData['qus_id'] = this.paper.qus_id;

                this.$http.post(postUrl, postData).then(function(resp) {
                    if (resp.data.status === 1) {
                        this.notice = {type: 1, msg: resp.data.message};
                        if (!que.que_id) {
                            que.que_id = resp.data.data;
                            this.ques.$set(index, que);
                        }
                        // 备份
                        que.contentBak = que.que_content;
                        que.scoreBak = que.que_score;
                        que.itemsBak = que.que_items.concat();
                        que.answerBak = que.que_type==2?que.que_answer.concat():que.que_answer;
                    } else {
                        this.notice = {type: 0, msg: resp.data.message};
                    }
                    que.editing = false;
                }, function(resp) {
                    // error callback
                    this.notice = {type: 0, msg: resp.statusText};
                })
            },
            chagePaperStatus: function() {
                if (!this.ques.length && this.paper.qus_status === 0) {
                    this.notice = {type: 0, msg: '请先添加题目'};
                }
                this.$http.post('/questionSet/changeStatus', {qus_id: this.paper.qus_id}).then(function(resp) {
                    if (resp.data.status === 1) {
                        this.notice = {type: 1, msg: resp.data.message};
                        this.paper.qus_status = this.paper.qus_status == 2 || this.paper.qus_status == 0 ? 1 : 2;
                    } else {
                        this.notice = {type: 0, msg: resp.data.message};
                    }
                }, function(resp) {
                    // error callback
                    this.notice = {type: 0, msg: resp.statusText};
                })
            }
        }
    }
</script>

<style>
@import './style.css';
</style>